package com.qf.filter;

import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * 自定义网关过滤器1
 * @author fy
 * @version V1.0
 * @Project workspace
 * @Package com.qf.filter
 * @Description:
 * @Date 2022/7/8 8:36
 */
@Component
public class Filter1 implements GlobalFilter , Ordered {
    /**
     * 编写这里需要的业务，，请求进来会先执行这些过滤器中的代码，执行后，请求才会被网关分发
     * @param exchange
     * @param chain
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        System.out.println("==============filter1===============");

        //1.获取请求头中的token令牌（加密字符串）
        //获取请求对象
        ServerHttpRequest request = exchange.getRequest();
        //获取响应对象
        ServerHttpResponse response = exchange.getResponse();
        //获取请求头中第一个叫做token的字符串
        String token = request.getHeaders().getFirst("token");

        //2.如果获取不到token，就认为没有权限访问，抛出401权限不足异常
        if (StringUtils.isEmpty(token)){
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            //通过响应对象返回异常信息
            return response.setComplete();
        }

        //3.判断如果获取到token就认为有权限，放行

        //放行，继续执行下一个过滤器
        return chain.filter(exchange);
    }

    /**
     * 返回的数字。如果有多个过滤器，就是过滤器的执行顺序
     * @return
     */
    @Override
    public int getOrder() {
        return 0;
    }
}
